package com.cw.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.cw.demo.model.Dept;
import com.cw.demo.service.DeptService;
import com.cw.demo.service.impl.DeptServiceImpl;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/findDept")
public class DeptController extends HttpServlet {

//    private DeptService deptService = new DeptServiceImpl();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //因为交给Spring来管理后，此时，直接再实例化的话，得到的对象，不是从spring的容器中获取的
        //需要从spring的容器中，取到 service
        //这一行代码，就是从 spring的配置文件中，根据bean的id来获取bean的实例化对象
        DeptService deptService = (DeptService) WebApplicationContextUtils.getWebApplicationContext(getServletContext()).getBean("deptService");
        //向控制台打印一下，当前获取的Service的对象是否为同一个？
        System.out.println(deptService);

        List<Dept> deptList = deptService.findByParam(null);
        //将结果返回回去
        //如果要将对象类型转换为json格式，需要添加一个工具类：fastJson
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write(JSONObject.toJSONString(deptList));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
